<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016 杭州博也网络科技, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace Shop\Controller;
use Common\Api\BoyeServiceApi;
use Shop\Api\AddressApi;
use Shop\Api\OrdersApi;
use Shop\Api\OrdersContactInfoApi;
use Shop\Api\OrdersExpressApi;
use Shop\Api\OrdersItemApi;
use Shop\Api\OrderStatusApi;
use Shop\Api\OrderStatusHistoryApi;
use Shop\Model\OrdersModel;
use Shop\Model\OrderStatusHistoryModel;
use Think\Controller;
use Tool\Api\ProvinceApi;
use Shop\Api\ShoppingCartApi;
use Shop\Api\MemberConfigApi;
use Admin\Api\UidMgroupApi;
use Shop\Api\HasIdcodeApi;

class OrdersController extends ShopController {

	/**
	 * 
	 * 访问前判断是否登录
	 */
	
	public function _initialize(){
        parent::_initialize();
        $this->checkLogin();
    }

    /**
     * 申请售后
     */
    public function after(){

        $this->redirect(('Shop/Article/index?id=4'));
//        $this->theme($this->themeType)->display();
    }

    /**
     *
     * 订单详情页
     * @author hebidu <hebiduhebi@126.com>
     * @date  15/11/13 17:51
     * @copyright by itboye.com  
     */ 
    public function  view(){
        $order_code = $this->_get('code',"","缺少订单编号!");
        $uid = $this->userinfo['uid'];

        $map = array(
            'order_code'=>$order_code,
            'uid'=>$uid,
        );


        $result = apiCall(OrdersApi::GET_INFO,array($map));
        $this->checkApiCallResult($result);
        $order_info = $result['info'];
        if($result['status']){
            $this->assign("order_info",$order_info);
        }

        $result = apiCall(OrdersContactInfoApi::GET_INFO,array($map));
        if($result['status']){
            $this->assign("contact_info",$result['info']);
        }

        $result = apiCall(OrdersItemApi::QUERY_NO_PAGING,array($map));
        if($result['status']){
            $this->assign("item_list",$result['info']);
        }

        $result = apiCall(OrderStatusHistoryApi::QUERY_NO_PAGING,array($map));

        if($result['status']){
            $timeline = $this->pickupTimeline($result['info']);
            $this->assign("timeline",$timeline);
        }

        $result = apiCall(OrdersExpressApi::GET_INFO,array($map));

        if($result['status']){
            $this->assign("express",$result['info']);
        }

        $this->theme($this->themeType)->display();
    }

    /**
     *
     * ajax返回订单数据
     * type = 0  有效订单 ,1 = 待支付 2 = 待收货  3 ＝ 已关闭
     * @author hebidu <hebiduhebi@126.com>
     * @date  15/11/13 15:41
     * @copyright by itboye.com
     */
    public function ajax_list(){

        $type = I('post.type', 0, 'intval');
        $p = I('post.p', 0, 'intval');
        //是否获取物流信息
        $uid=$this->userinfo['uid'];

        $page = array('curpage'=>$p,'size'=>10);
        $order = " updatetime desc ";
        $result = apiCall(OrdersApi::QUERY_ALL_INFO,array($type,$uid,$page,$order,array()));

        if($result['status']){
            $list = $this->transformData($result['info']['list']);

            $this->success(array('list'=>$list,'show'=>$result['info']['show']),"",true);
        }else{
            $this->error($result['info'],"",true);
        }
    }


	/**
	 * 取消订单
	 */
	public function cancel(){

        $order_code = I('param.order_code',"");

        if(empty($order_code)){
            $this->error("订单参数缺失!");
        }

        $uid = $this->userinfo['uid'];
		$result=apiCall(OrderStatusApi::CANCEL,array($order_code,false,$uid));
		if($result['status']){
			$this->success('取消成功!');
		}else{
			$this->error('取消失败!');
		}
		
	}

	/*
	 * 确认收货
	 * */
	public function receive(){
        $order_code = I('get.order_code',"");

        if(empty($order_code)){
            $this->error("订单参数缺失!");
        }

        $uid = $this->userinfo['uid'];
		$result=apiCall(OrderStatusApi::CONFIRM_RECEIVE,array($order_code,false,$uid));
		if($result['status']){
			$this->success('成功确认收货!');
		}else{
			$this->error('确认收货失败!');
		}
		
	}


    public function checkout(){

        $cart_id_arr = I('post.cart_id','');
        if(empty($cart_id_arr)){
            $cart_id_arr =  I('get.cart_id','');
            $cart_id_arr = array($cart_id_arr);
        }

        if(empty($cart_id_arr)) {
            $this->error("参数缺失!");
        }
        $direct = $this->_get('direct',0);

        $this->assign("cart_id",$cart_id_arr);
        session("buy_cart_id",$cart_id_arr);
        if($direct){//直接跳转-立即购买
            $this->redirect('Shop/Orders/confirm');
        }else{//购物车结算
            $this->success("前往确认订单!",U('Shop/Orders/confirm'));
        }
    }


    /**
     *
     * 订单确认
     * @author hebidu <hebiduhebi@126.com>
     * @date  15/11/9 16:54
     * @copyright by itboye.com
     */
    public function confirm(){

        $cart_id_arr = session("buy_cart_id");
        if(empty($cart_id_arr)){
            $this->clearCartItemCache();
            $this->error("请重新选择商品!",U('Shop/Index/index'));
        }
        $uid = $this->userinfo['uid'];
        $map = array(
            'uid'=>$uid,
        );
        $page = array('curpage'=>1,'size'=>6);
        $order = " id desc ";

        $result = apiCall(AddressApi::QUERY,array($map,$page,$order));

        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
        }

        $address = $result['info']['list'];
        $this->assign("address",$address);

        $map = array(
            'countryid'=>1017
        );

        $result = apiCall(ProvinceApi::QUERY_NO_PAGING,array($map));
        if($result['status']){
            $this->assign("province",$result['info']);
        }

        $this->assign("default_address",$this->userinfo['default_address']);
        $map = array(
            'uid'=>$this->userinfo['uid'],
            'id'=>array('in',$cart_id_arr)
        );

        $result = apiCall(ShoppingCartApi::QUERY_NO_PAGING,array($map));
        $cart = $result['info'];

        if($result['status']){
            session("order_cart",$cart);
            $this->assign("cart",$cart);
            $total_price = $this->getTotalPrice($cart);
            $this->assign("total_price",$total_price);
            $discount_price = $this->getDiscountPrice($cart);
            $this->assign("discount_price",$discount_price);
            $tax_price = $this->getTaxPrice($cart);
            $this->assign("tax_price",$tax_price);
        }

        //1. 获取历史优惠码
        $map = array(
            'uid'=>$uid,

        );
        $page = array('curpage'=>1,'size'=>30);
        $order = " id desc ";
        $result = apiCall(HasIdcodeApi::QUERY,array($map,$page,$order));

        if($result['status']){
            $this->assign("idcode_list",$result['info']['list']);
        }

        $this->theme($this->themeType)->display();
    }

    /**
     * 优惠金额
     * @return int
     */
    public function calByIDCode(){

        $idcode = I('post.idcode','');
        $cart = session("order_cart");

        if(empty($cart)){
            $this->error("Session失效!");
        }

        if(empty($idcode)){
            $this->error("0");
        }

        if($idcode == $this->userinfo['idcode']){
            $this->error("不能填自己的优惠码!");
        }

        $result = apiCall(MemberConfigApi::GET_INFO,array(array('idcode'=>$idcode)));

        $this->checkApiCallResult($result);


        $uid = $result['info']['uid'];

        //1. 获取各个店铺的优惠比例
        $result = apiCall(UidMgroupApi::QUERY_WITH_UID,array($uid));

        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
        }

        $other_discount_arr = $result['info'];
        if(empty($other_discount_arr)) {
            $this->success(0.00);
        }
        $tmp_arr = array();
        foreach($other_discount_arr as $vo) {
            $tmp_arr[$vo['store_id']] = $vo;
        }

        $dis_price = 0;
        foreach($cart as $vo){
            $dis_info = $tmp_arr[$vo['store_id']];
            if(!empty($dis_info)){
                $ratio = $dis_info['discount_ratio'];
                $dis_price = $dis_price + ($vo['count'] * $vo['price'] * $ratio);
            }
        }

        $this->success(round($dis_price,2));
    }

    /**
     * 订单添加
     */
    public  function add(){

        //1. 购物车 从session中的获取购买物品ID
        $buy_cart_id = session("buy_cart_id");
        $addr_id = $this->_post("addressid",'','请选择收货地址!');
        $idcode = $this->_post("idcode",""); //优惠码
        $pay_type = $this->_post("pay_type","","请选择支付方式!");
        $service = new BoyeServiceApi();
        $data = array();
        $data['uid'] = $this->userinfo['id'];
        $data['addr_id'] = $addr_id;
        $data['idcode'] = $idcode;
        $data['from'] = OrdersModel::COME_FROM_PC;
        $data['cart_ids'] = $cart_ids;
        $data['payType'] = $pay_type;

        //1. 购物车id 字符串
        $buy_cart_id_str = "";

        foreach($buy_cart_id as $vo){
            if(strlen($buy_cart_id_str) > 0){
                $buy_cart_id_str = $buy_cart_id_str.",";
            }
            $buy_cart_id_str = $buy_cart_id_str . $vo;
        }

        if(empty($buy_cart_id_str)){
            $this->error("购物车信息缺失!");
        }

        $data['cart_ids'] = $buy_cart_id_str;

        $result = $service->callRemote("Orders/add",$data);
        addLog("Orders/add",$result,"","[远程订单添加返回结果]");

        $info = $result['info'];
        if($result['status'] && $info['code'] == 0){
            $data = $info['data'];
            //2. 清除session中的购物车
            session("buy_cart_id",null);
            //3. 清除用于方便优惠计算的购买的商品信息
            session("order_cart",null);
            $this->jumpToPay($pay_type,$data);
        } else{
            $this->error($info['data']);
            LogRecord("Orders/add",__FILE__.__LINE__);
        }

        $this->error("生成订单失败!");

    }

    /**
     * 重新发起单个订单支付
     */
    public function repay(){

        $service = new BoyeServiceApi();
        $order_id = $this->_get("id",0,"缺少订单ID");
        $data = array(
            'uid'=>$this->userinfo['uid'],
            'order_id'=>$order_id,
            'pay_type'=>OrdersModel::PAY_TYPE_ALIPAY,
        );
        //1. 调用接口
        $result = $service->callRemote("Orders/pay",$data);

        $info = $result['info'];
        if($result['status'] && $info['code'] == 0){
            $data = $info['data'];
            $this->jumpToPay(OrdersModel::PAY_TYPE_ALIPAY,$data);
        } else{
            $this->error($info['data']);
            LogRecord("Orders/repay",__FILE__.__LINE__);
        }

        $this->error("重新支付失败!");

    }

    //*** PRIVATE私有方法**************************************************************************

    private function pickupTimeline($list){

        $timeline =  array(
//            'pay_time'=>'',//支付时间
//            'shipped_time'=>'',//发货时间
//            'received_time'=>'',//收货时间
//            'completed_time'=>'',//交易成功时间
        );

        foreach($list as $vo){
            $status_type = strtolower($vo['status_type']);
            if($status_type == strtolower(OrderStatusHistoryModel::STATUS_TYPE_PAY)
                && $vo['cur_status'] == OrdersModel::ORDER_TOBE_PAID){
                $timeline['pay_time'] = $vo['create_time'];
            }
            elseif($status_type == strtolower(OrderStatusHistoryModel::STATUS_TYPE_ORDER)){
                if($vo['next_status'] == OrdersModel::ORDER_SHIPPED){
                    $timeline['shipped_time'] = $vo['create_time'];
                }elseif($vo['next_status'] == OrdersModel::ORDER_RECEIPT_OF_GOODS){
                    $timeline['received_time'] = $vo['create_time'];
                }elseif($vo['next_status'] == OrdersModel::ORDER_COMPLETED){
                    $timeline['completed_time'] = $vo['create_time'];
                }
            }

        }
        return $timeline;

    }

    /**
     * $pay_type = 1 ;//国际支付宝
     * $pay_type = 2 ;//微信支付
     * @param $pay_type
     * @param $data
     */
    private function jumpToPay($pay_type,$data){

        if($pay_type == 1){
            if(is_array($data)){
                $code = $data['code'];
                $name = ($data['name']);
                $desc = ($data['desc']);
                $total_price = $data['total_price'];
                $key = $data['key'];

                $this->success("跳转支付!", U('Shop/GAlipay/pay?key='.$key.'&desc='.$desc.'&code='.$code.'&name='.$name.'&total_price='.$total_price),true);
            }else{
                $this->error("支付信息缺失!");
            }
        }


        $this->error("不支持的支付方式!");


    }

    /**
     * 获取订单总计
     * @param $cart
     * @return int
     */
    private function getTotalPrice($cart){
        $total_price = 0;
        foreach($cart as $vo){
            $total_price = $total_price + ($vo['count'] * $vo['price']);
        }
        return round_pad_zero($total_price,2);

    }

    /**
     * 优惠金额
     * @param $cart
     * @return int
     */
    private function getDiscountPrice($cart){

        $uid = $this->userinfo['uid'];
        //1. 获取各个店铺的优惠比例
        $result = apiCall(UidMgroupApi::QUERY_WITH_UID,array($uid));

        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
        }
        $self_discount_arr = $result['info'];
        $tmp_arr = array();
        foreach($self_discount_arr as $vo){
            $tmp_arr[$vo['store_id']] = $vo;
        }

        $dis_price = 0;
        foreach($cart as $vo){
            $dis_info = $tmp_arr[$vo['store_id']];
            if(!empty($dis_info)){
                $ratio = $dis_info['discount_ratio'];
                $dis_price = $dis_price + ($vo['count'] * $vo['price'] * $ratio);
            }
        }
        return round_pad_zero($dis_price,2);
    }

    /**
     * 税额
     * @param $cart
     * @return int
     */
    private function getTaxPrice($cart){
        $tax_price = 0;
        foreach($cart as $vo){
            $tax_price = $tax_price + $vo['taxrate'] * ($vo['count'] * $vo['price']);
        }

        $duty_free_price = C('DUTY_FREE_PRICE');
        $duty_free_price = floatval($duty_free_price);
        if($tax_price <= $duty_free_price){
            $tax_price = 0;
        }

        return round_pad_zero($tax_price,2);
    }

    private function transformData($list){

        $order_list = array();
        foreach($list as $vo){
            $entity = array(
                'id' => $vo['id'],
                'pay_type'=>getPayType($vo['pay_type']),
                'order_code' => $vo['order_code'],
                'price' => round($vo['price'],2), //订单总价
                'store_id' => $vo['storeid'],
                'order_status'=>$vo['order_status'],
                'create_date'=>date("Y年m月d日 H:i",$vo['createtime']),
                'comment_status'=>$vo['comment_status'],
                'order_status_desc'=> getTaobaoOrderStatus($vo['order_status']),
                'pay_status'=>$vo['pay_status'],
                'contactname'=>$vo['contactname'],
                '_items' => array(), //商品列表
            );
            $key = $vo['order_code'];
            $item = array(
                'p_id'=>$vo['item_p_id'],
                'price'=>$vo['item_price'],
                'count'=>$vo['count'],
                'sku_desc'=>$vo['sku_desc'],
                'name'=>$vo['name'],
                'img'=>getImageUrl($vo['img'],80),
            );
            if(isset($order_list[$key])){
                array_push($order_list[$key]['_items'],$item);
            }else{
                array_push($entity['_items'],$item);
                $order_list[$key] = $entity;
            }

        }
        return $order_list;
    }


}
